import { createRouter as createVueRouter, createWebHistory<% if (applicationTypeGateway && microfrontend) { %>, type RouteRecordRaw<% } %> } from 'vue-router';
<%_ if (applicationTypeGateway && microfrontend) { _%>
import { loadRemote } from '@module-federation/enhanced/runtime';
<%_ } _%>

const Home = () => import('@/core/home/home.vue');
const Error = () => import('@/core/error/error.vue');
<%_ if (generateUserManagement) { _%>
import account from '@/router/account';
<%_ } _%>
import admin from '@/router/admin';
import entities from '@/router/entities';
import pages from '@/router/pages';

export const createRouter = () =>   createVueRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/forbidden',
      name: 'Forbidden',
      component: Error,
      meta: { error403: true }
    },
    {
      path: '/not-found',
      name: 'NotFound',
      component: Error,
      meta: { error404: true }
    },
<%_ if (generateUserManagement) { _%>
    ...account,
<%_ } _%>
    ...admin,
    entities,
    ...pages
  ]
});

const router = createRouter();

<%_ if (applicationTypeGateway && microfrontend) { _%>
export const lazyRoutes = Promise.all([
  <%_ for (const remote of microfrontends) { _%>
  loadRemote<any>('<%= remote.lowercaseBaseName %>/entities-router')
    .then(<%= remote.lowercaseBaseName %>Router => {
      router.addRoute(<%= remote.lowercaseBaseName %>Router.default as RouteRecordRaw);
      return <%= remote.lowercaseBaseName %>Router.default;
    }).catch(error => {
      console.log(`Error loading <%= remote.lowercaseBaseName %> menus. Make sure it's up. ${error}`);
    }),
  <%_ } _%>
]);

<%_ } _%>
router.beforeResolve(async (to, from, next) => {
  if (!to.matched.length) {
<%_ if (applicationTypeGateway && microfrontend) { _%>
    await lazyRoutes;
    if (router.resolve(to.fullPath).matched.length > 0) {
      next({ path: to.fullPath });
      return;
    }

<%_ } _%>
    next({ path: '/not-found' });
    return;
  }
  next();
});

export default router;
